package com.gamelife.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gamelife.web.domain.entity.SysUser;
import com.gamelife.web.exception.ServiceException;
import com.gamelife.web.mapper.SysUserMapper;
import com.gamelife.web.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hsx
 * @since 2022-06-27
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Override
    public SysUser selectUserByUserName(String username) {
        return getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));
    }

    @Override
    public List<SysUser> selectList(String username, Integer pageNum, Integer pageSize) {
        // 查询条件
        LambdaQueryWrapper<SysUser> wrapper =
                new LambdaQueryWrapper<SysUser>().eq(!StringUtils.isNullOrEmpty(username),
                        SysUser::getUsername, username);
        // 分页查询
        List<SysUser> sysUserList = baseMapper.selectPage(new Page<>(pageNum, pageSize),
                wrapper).getRecords();
        // 覆盖掉密码
        return sysUserList.stream()
                .peek(sysUser -> sysUser.setPassword(""))
                .collect(Collectors.toList());
    }


    @Override
    public Boolean insertSysUser(SysUser sysUser) {
        // 添加时间
        LocalDateTime now = LocalDateTime.now();
        sysUser.setCreated(now);
        sysUser.setUpdated(now);
        try {
            save(sysUser);
        } catch (RuntimeException e) {
            throw new RuntimeException("用户添加失败");
        }
        return true;
    }

    @Override
    public Boolean updateSysUser(SysUser sysUser) {
        // 更新时间
        LocalDateTime now = LocalDateTime.now();
        sysUser.setUpdated(now);
        try {
            updateById(sysUser);
        } catch (RuntimeException e) {
            throw new RuntimeException("用户信息更新失败");
        }
        return true;
    }

    @Override
    public SysUser selectUserByUserId(Long userId) {
        SysUser sysUser;
        try {
            sysUser =
                    getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, userId));
        } catch (Exception e) {
            throw new RuntimeException("用户信息获取失败");
        }
        return sysUser;
    }

}
